package com.wind.plugin.configuration.configUI;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.JBList;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wind
 * @version 1.0
 * @description: TODO
 * @date 2025/2/17 15:03
 */
public class HighLightFieldPanel extends JPanel implements Disposable {

    private JBList<String> fieldList;
    private DefaultListModel<String> fieldListModel;

    public HighLightFieldPanel() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(0, 250));
        this.setBorder(IdeBorderFactory.createTitledBorder("Highlight Filed 要高亮的Java代码字段"));
        fieldListModel = new DefaultListModel<>();
        fieldList = new JBList<>(fieldListModel);
        fieldList.setVisibleRowCount(5);
        JPanel classTablePanel = ToolbarDecorator.createDecorator(fieldList)
                .setAddAction(it -> addFieldAction())
                .setRemoveAction(it -> removeFieldAction()).disableUpDownActions()
                .setEditAction(it -> editAction())
                .createPanel();
        this.add(classTablePanel, BorderLayout.CENTER);
    }

    private void editAction() {
        int selectedRow = fieldList.getSelectedIndex();
        if (selectedRow != -1) {
            String value = fieldListModel.getElementAt(selectedRow);
            String input = Messages.showInputDialog(
                    "请输入要高亮的Java代码中的字段（如cur）",
                    "添加java中字段",
                    Messages.getInformationIcon(),
                    value,
                    null
            );
            if (input != null && !input.trim().isEmpty()) {
                fieldListModel.set(selectedRow, input.trim());
            }
        }
    }

    private void addFieldAction() {
        String input = Messages.showInputDialog(
                "请输入要高亮的Java代码中的字段（如cur）",
                "添加java中字段",
                Messages.getInformationIcon()
        );
        if (input != null && !input.trim().isEmpty()) {
            fieldListModel.addElement(input.trim());
        }
    }

    private void removeFieldAction() {
        int selectedRow = fieldList.getSelectedIndex();
        if (selectedRow != -1) {
            fieldListModel.removeElementAt(selectedRow);
        }
    }

    public void setFieldList(java.util.List<String> classes) {
        fieldListModel.clear();
        for (String aClass : classes) {
            fieldListModel.addElement(aClass);
        }
    }

    public java.util.List<String> getHighlightFields() {
        List<String> res = new ArrayList<>();
        for (int i = 0; i< fieldListModel.getSize(); i++) {
            res.add(fieldListModel.getElementAt(i));
        }
        return res;
    }

    @Override
    public void dispose() {

    }
}
